﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Xml.Linq;
using System.Web.UI.HtmlControls;

namespace Framework
{
    public partial class Contact : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public List<udv_Categories> allCate = new List<udv_Categories>();
        public List<udv_Articles> allArt = new List<udv_Articles>();
        public List<udv_Products> allPro = new List<udv_Products>();

        protected void Page_Load(object sender, EventArgs e)
        {

            RequiredFieldValidator1.ErrorMessage = Globals.GetLanguage("Vui lòng nhập họ tên hoặc công ty", "Please enter name or company", true);
            txtName.Attributes["placeholder"] = Globals.GetLanguage("Họ tên/Công ty", "Name/Company", true);
            RequiredFieldValidator2.ErrorMessage = Globals.GetLanguage("Vui lòng nhập địa chỉ", "Please enter the address", true);
            txtAddress.Attributes["placeholder"] = Globals.GetLanguage("Địa chỉ", "Address", true);
            RequiredFieldValidator4.ErrorMessage = Globals.GetLanguage("Vui lòng nhập điện thoại", "Please enter the phone", true);
            txtPhone.Attributes["placeholder"] = Globals.GetLanguage("Điện thoại", "Phone", true);
            RequiredFieldValidator3.ErrorMessage = Globals.GetLanguage("Vui lòng nhập email", "Please enter the e-mail", true);
            RegularExpressionValidator1.ErrorMessage = Globals.GetLanguage("Email không đúng định dạng", "Email is malformed", true);
            txtEmail.Attributes["placeholder"] = "Email";
            RequiredFieldValidator5.ErrorMessage = Globals.GetLanguage("Vui lòng nhập tiêu đề liên hệ", "Please enter a contact title", true);
            txtTitle.Attributes["placeholder"] = Globals.GetLanguage("Chủ đề", "Title", true);
            RequiredFieldValidator6.ErrorMessage = Globals.GetLanguage("Vui lòng nhập nội dung", "Please enter the message", true);
            RegularExpressionValidator2.ErrorMessage = Globals.GetLanguage("Nội dung liên hệ ít nhất phải 20 ký tự", "Contact content must be at least 20 characters", true);
            txtContent.Attributes["placeholder"] = Globals.GetLanguage("Vui lòng nhập tiếng việt", "Please type here", true);
            btnSend.Text = Globals.GetLanguage("Gửi", "Send", true);
            btnReset.Text = Globals.GetLanguage("Làm lại", "Redo", true);

            //LoadInfomation();
            if (!IsPostBack)
            {
                LoadCacheCategory();
                LoadCacheArticle();
                LoadCacheProduct();
                AddTag("", "", "Liên hệ", "Liên hệ");
            }
        }

        public void LoadCacheCategory()
        {
            if (Cache["Category"] == null)
            {
                Cache["Category"] = allCate = entity.udv_Categories.ToList();
            }
            else
            {
                allCate = (List<udv_Categories>)Cache["Category"];
            }
        }

        public void LoadCacheArticle()
        {
            if (Cache["Article"] == null)
            {
                Cache["Article"] = allArt = entity.udv_Articles.Include("udv_Categories").ToList();
            }
            else
            {
                allArt = (List<udv_Articles>)Cache["Article"];
            }
        }

        public void LoadCacheProduct()
        {
            if (Cache["Product"] == null)
            {
                Cache["Product"] = allPro = entity.udv_Products.Include("udv_Categories").ToList();
            }
            else
            {
                allPro = (List<udv_Products>)Cache["Product"];
            }
        }

        public string GetDefaultTitlePage()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("Title").Value.Trim();
        }

        public string GetDefaultMetaDescription()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaDescription").Value.Trim();
        }

        public string GetDefaultMetaKeyword()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaKeywords").Value.Trim();
        }

        public string GetDefaultMetaTitle()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

            XElement xEInfomationConfigWebsite = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xEInfomationConfigWebsite.Element("MetaTitle").Value.Trim();
        }

        public void AddTag(string metaDescription, string metaKeywords, string metaTitle, string pageTitle)
        {
            if (string.IsNullOrEmpty(metaDescription))
            {
                metaDescription = GetDefaultMetaDescription();
            }
            if (string.IsNullOrEmpty(metaKeywords))
            {
                metaKeywords = GetDefaultMetaKeyword();
            }
            if (string.IsNullOrEmpty(pageTitle))
            {
                pageTitle = GetDefaultTitlePage();
            }
            if (string.IsNullOrEmpty(metaTitle))
            {
                metaTitle = GetDefaultMetaTitle();
            }
            HtmlHead headTag = (HtmlHead)this.Master.FindControl("Head1");
            headTag.Title = pageTitle;
            HtmlMeta PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "description";
            PagemetaTag.Content = metaDescription;
            headTag.Controls.AddAt(2, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "keywords";
            PagemetaTag.Content = metaKeywords;
            headTag.Controls.AddAt(3, PagemetaTag);
            PagemetaTag = new HtmlMeta();
            PagemetaTag.Name = "title";
            PagemetaTag.Content = metaTitle;
            headTag.Controls.AddAt(4, PagemetaTag);
        }

        //public void LoadInfomation()
        //{
        //    XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));

        //    XElement xEInfomationCompany = xDocInfo.Descendants("company").FirstOrDefault();
        //    ltrCompanyName.Text = Globals.GetLanguage(xEInfomationCompany.Element("companyname").Value.Trim(), xEInfomationCompany.Element("companyname_en").Value.Trim(), true);
        //    ltrAddress.Text = Globals.GetLanguage(xEInfomationCompany.Element("address").Value.Trim(), xEInfomationCompany.Element("address_en").Value.Trim(), true);
        //    ltrEmail.Text = "<a href='" + "mailto:" + xEInfomationCompany.Element("email").Value.Trim() + "'>" + xEInfomationCompany.Element("email").Value.Trim() + "</a>";
        //    ltrPhone.Text = xEInfomationCompany.Element("phone").Value.Trim();
        //    ltrFax.Text = xEInfomationCompany.Element("fax").Value.Trim();
        //    ltrWebsite.Text = "<a href='http://" + xEInfomationCompany.Element("website").Value.Trim() + "' title='" + xEInfomationCompany.Element("website").Value.Trim() + "'>" + xEInfomationCompany.Element("website").Value.Trim() + "</a>";
        //    ltrGoogleMap.Text = xEInfomationCompany.Element("image_map").Value.Trim();
        //}

        public void InsertDb()
        {
            udv_Contact obj = new udv_Contact()
            {
                Title = Server.HtmlEncode(txtTitle.Text.Trim()),
                AddedDate = DateTime.Now,
                Address = Server.HtmlEncode(txtAddress.Text.Trim()),
                Content = Server.HtmlEncode(txtContent.Text.Trim()),
                Email = Server.HtmlEncode(txtEmail.Text.Trim()),
                FullName = Server.HtmlEncode(txtName.Text.Trim()),
                Tel = Server.HtmlEncode(txtPhone.Text.Trim()),
                ViewStatus = false,
                ReplyStatus = false
            };

            entity.AddToudv_Contact(obj);
            entity.SaveChanges();
        }

        private bool SendEmail()
        {
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            string serverMail = emailHostSetting.ServerMailSMTP.Trim();
            string port = emailHostSetting.PortMailSMTP.ToString();
            string yourMailAccount = emailHostSetting.MailAccount.Trim();
            string yourMailPassword = Globals.Base64Decode(emailHostSetting.Password.Trim());

            SendMail sm = new SendMail();
            sm.ServerMail = serverMail;
            sm.ServerPort = port;
            sm.SSL = emailHostSetting.SSL.Value;
            sm.YourMailAccount = yourMailAccount;
            sm.YourMailPassword = yourMailPassword;
            sm.SetUpYourServerMail();

            string receive = yourMailAccount;

            XDocument xDocContact = XDocument.Load(Server.MapPath(ConfigPaths.Path_ContactGroup_Xml));
            var listXEContact = xDocContact.Descendants("contact_group")
                .Select(cg => new
                {
                    ID = cg.Element("id").Value.Trim(),
                    Mail = cg.Element("mail").Value.Trim(),
                    ShowName = cg.Element("showname").Value.Trim(),
                    ShowName_en = cg.Element("showname").Value.Trim(),
                    Index = cg.Element("index").Value.Trim(),
                    Group = cg.Element("group").Value.Trim()
                })
                .ToList();
            foreach (var item in listXEContact)
            {
                receive += item.Mail + ",";
            }

            string title = txtTitle.Text.Trim();

            string body = "<p><b>Họ tên:</b> " + txtName.Text.Trim() + "</p>";
            body += "<p><b>Địa chỉ:</b> " + txtAddress.Text.Trim() + "</p>";
            body += "<p><b>Điện thoại:</b> " + txtPhone.Text.Trim() + "</p>";
            body += "<p><b>Email:</b> " + txtEmail.Text.Trim() + "</p>";
            body += "<p><b>Nội dung liên hệ:</b></p>";
            body += "<p>" + txtContent.Text + "</p>";

            sm.CreateMailObject(receive, body, title, emailHostSetting.MailReceive);
            if (sm.MailSending())
            {
                InsertDb();
                return true;
            }
            else
            {
                InsertDb();
                return false;
            }
        }

        void ResetAllFields()
        {
            txtTitle.Text = "";
            txtAddress.Text = "";
            txtName.Text = "";
            txtContent.Text = "";
            txtEmail.Text = "";
            txtPhone.Text = "";
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            //recaptcha.Validate();
            //if (recaptcha.IsValid)
            //{
            //    lblCaptchaMessage.InnerText = "";
                InsertDb();
                //SendEmail();
                lblAlertContact.Text = "Chúng tôi đã nhận được liên hệ của bạn.";
                ResetAllFields();
            //}
            //else
            //{
            //    lblCaptchaMessage.InnerText = "Nhập sai mã xác nhận. Vui lòng thử lại";
            //}
            //pbTarget.Visible = true;
            //ScriptManager.RegisterClientScriptBlock(
            //  recaptcha,
            //  recaptcha.GetType(),
            //  "recaptcha",
            //  "Recaptcha._init_options(RecaptchaOptions);"
            //  + "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
            //  + "{"
            //  + "  if ( RecaptchaOptions.custom_theme_widget )"
            //  + "  {"
            //  + "    Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
            //  + "    Recaptcha.challenge_callback();"
            //  + "  }"
            //  + "} else {"
            //  + "  if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
            //  + "  {"
            //  + "    jQuery(\"#" + pbTarget.ClientID + "\").html('<div id=\"recaptcha_widget_div\" style=\"display:none\"></div>');"
            //  + "    Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
            //  + "  }"
            //  + "  Recaptcha.reload();"
            //  + "  Recaptcha.challenge_callback();"
            //  + "}",
            //  true
            //);
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            //recaptcha.Validate();
            ResetAllFields();
            //pbTarget.Visible = true;
            //ScriptManager.RegisterClientScriptBlock(
            //  recaptcha,
            //  recaptcha.GetType(),
            //  "recaptcha",
            //  "Recaptcha._init_options(RecaptchaOptions);"
            //  + "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
            //  + "{"
            //  + "  if ( RecaptchaOptions.custom_theme_widget )"
            //  + "  {"
            //  + "    Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
            //  + "    Recaptcha.challenge_callback();"
            //  + "  }"
            //  + "} else {"
            //  + "  if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
            //  + "  {"
            //  + "    jQuery(\"#" + pbTarget.ClientID + "\").html('<div id=\"recaptcha_widget_div\" style=\"display:none\"></div>');"
            //  + "    Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
            //  + "  }"
            //  + "  Recaptcha.reload();"
            //  + "  Recaptcha.challenge_callback();"
            //  + "}",
            //  true
            //);
        }

    }
}